'''Contains the functions needed to validate various claim information.'''
from re import (
    match as re_match,
    search as re_search,
    I as re_I,
)
from os.path import (
    basename as os_path_basename,
    splitext as os_path_splitext,
    isfile as os_path_isfile,
)


def get_extension(file_path):
    '''Determines the file extension for a given file name or path.'''
    return os_path_splitext(file_path)[1]


def validate_extension(file_path, expected_extensions):
    '''Ensures the provided file extension matches the expected one.'''
    stripped_file_path = file_path.strip()
    provided_extension = get_extension(stripped_file_path)

    for expected_extension in expected_extensions:

        if re_match(expected_extension, provided_extension, flags=re_I):
            return stripped_file_path

    return None


def validate_file(file_path, expected_extensions):
    '''
    Ensures the provided text is a valid path to an existing file,
    and not a folder.
    '''
    stripped_file_path = file_path.strip()
    file_name = os_path_basename(stripped_file_path)

    # To make sure that the file exists, and has the correct extension
    if os_path_isfile(stripped_file_path) and validate_extension(file_name, expected_extensions):
        return stripped_file_path

    return None


def validate_chromebook_keys(values):
    '''
    Ensures that Chromebook keys are entered in a valid format.
    '''
    for key in values.values():
        stripped_key = key.strip()

        if not stripped_key:
            return False

    return {values[key].strip() for key in values}


def validate_part_numbers(values):
    '''
    Ensures that all HP part numbers entered are in a valid format.
    '''
    for part_num in values.values():
        stripped_part_num = part_num.strip()

        if not re_search(r'^\w{6}-\w{3}$', stripped_part_num):
            return False

    return {values[key].strip() for key in values}


def validate_notes(values):
    '''
    Ensures that all CSN notes contain at least one word character.
    '''
    for note in values.values():
        if not re_search(r'\w+', note):
            return False

    return {values[key].strip() for key in values}
